package com.example.manage.controller;

import com.example.manage.bean.ResultBean;
import com.example.manage.bean.UserBean;
import com.example.manage.mapper.UserMapper;
import com.example.manage.utils.MD5Util;
import com.example.manage.utils.ResultUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;
import java.util.Map;
import java.util.UUID;

@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    UserMapper userMapper;

    @RequestMapping("/addUser")
    @ResponseBody
    public ResultBean addUser(@RequestBody UserBean userBean) {
        String uuid = UUID.randomUUID().toString().replace("-", "");
        userBean.setUid(uuid);
        userBean.setPwd(MD5Util.MD5(userBean.getPwd()));
        int count = userMapper.addUser(userBean);
        return ResultUtil.getResultBean(count, "添加失败");
    }

    @RequestMapping("/updateUserByUid")
    @ResponseBody
    public ResultBean updateUserByUid(@RequestBody UserBean userBean) {
        userBean.setPwd(MD5Util.MD5(userBean.getPwd()));
        int count = userMapper.updateUserByUid(userBean);
        return ResultUtil.getResultBean(count, "修改失败");
    }

    @RequestMapping("/deleteUserByUid")
    @ResponseBody
    public ResultBean deleteUserByUid(@RequestBody Map<String, String> params) {
        int count = userMapper.deleteUserByUid(params.get("uid"));
        return ResultUtil.getResultBean(count, "删除失败");
    }

    @RequestMapping("/queryUser")
    @ResponseBody
    public ResultBean queryUser() {
        List<UserBean> userBeans = userMapper.queryUser();
        return ResultUtil.getSuccessBean(userBeans);
    }

    @RequestMapping("/login")
    @ResponseBody
    public ResultBean login(@RequestBody UserBean userBean) {
        UserBean user = userMapper.queryUserByPhone(userBean.getPhone());
        if (user == null) {
            return ResultUtil.getFailBean("无该用户");
        }
        if (user.getPwd().equals(userBean.getPwd())) {
            user.setPwd("");
            return ResultUtil.getSuccessBean(user);
        } else {
            return ResultUtil.getFailBean("密码不正确");
        }

    }

    @RequestMapping("/queryUserByPhone")
    @ResponseBody
    public ResultBean queryUserByPhone() {
        UserBean user = userMapper.queryUserByPhone("");
        return ResultUtil.getSuccessBean(user);
    }



}
